//
//  NetworkToos.swift
//  01-界面搭建
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking
///HTTP 请求方法枚举
enum HMRequestMethod:String {
    case GET = "GET"
    case POST = "POST"
    
}
class NetworkToos: AFHTTPSessionManager {
    //MARK: - 应用程序信息
    private let appKey = "3497782951"
    private let appSecret = "3fb58132ad81b6ff516fc8419f6680f4"
    private let redirectUrl = "http://www.baidu.com"
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias HMRequestCallBack = (result:AnyObject?,error:NSError?)->()
    //MARK: -单例
    static let shardTools:NetworkToos = {
        let tools = NetworkToos(baseURL: nil)
        //设置反序列化数据格式--系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
     /// 返回 token 字典
    private var tokenDic:[String:AnyObject]? {
        // 判断 token 是否有效
        if let token = UserAccountViewModel.shardViewModel.token {
        
          return ["access_token":token]
        
        }
    
    return nil
    }
}
// MARK: - 用户相关方法
extension NetworkToos {
    
    /// 加载用户信息
    ///
    /// - parameter uid:         uid
    /// - parameter accessToken: accessToken
    /// - parameter finished:    完成回调
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    
    func loadUserInfo(uid:String,finish:HMRequestCallBack) {
        let urlstring = "https://api.weibo.com/2/users/show.json"
          //  获取 token 字典
        guard var params = tokenDic else {
         // 如果字典为 nil，通知调用方，token 无效
            finish(result: nil, error: NSError(domain:  "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
        return
        }
     params["uid"] = uid
    
    request(.GET, URLString: urlstring, parameters: params, finish: finish)
    }


}
// MARK: - Home 相关方法
extension NetworkToos {
    /// 加载微博数据
    ///
    /// - parameter since_id:	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    /// - parameter max_id:     若指定此参数，则返回ID`小于或等于max_id`的微博，默认为0
    /// - parameter finished:   完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatuesInfo(since_id since_id: Int, max_id: Int,finish:HMRequestCallBack) {
        let urlstring = "https://api.weibo.com/2/statuses/home_timeline.json"
        //  获取 token 字典
        guard var params = tokenDic else {
            // 如果字典为 nil，通知调用方，token 无效
            finish(result: nil, error: NSError(domain:  "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            return
        }
        
        // 判断是否下拉
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {  // 上拉参数
            params["max_id"] = max_id - 1
        }
   request(.GET, URLString: urlstring, parameters: params, finish: finish)
    }
    



}
// MARK: - OAuth 相关方法
extension NetworkToos {
    //OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauth:NSURL {
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
    return NSURL(string: urlString)!
    }
     /// 加载 AccessToken
    func loadAccessToken(code: String, finished:HMRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
       request(.POST, URLString: urlString, parameters: params, finish: finished)
        //MARK: - 测试网络返回的数据的类型
        /*
        测试返回的数据内容 - AFN 默认的响应格式是 JSON，会直接反序列化
        确认数据格式的问题
        如果是 NSNumber，则没有引号！在做 KVC 指定属性类型非常重要！
        1> 设置相应数据格式是二进制的
        responseSerializer = AFHTTPResponseSerializer()
        2> 发起网络请求
        POST(urlString, parameters: params, success: { (_,result) -> Void in
        let json = NSString(data: result as! NSData , encoding: NSUTF8StringEncoding)
        print(json)
        }, failure: nil)
        
        {"access_token":"2.00ml8IrF6dP8NE6791982000uQBsmB",
        "remind_in":"157679999",
        "expires_in":157679999,
        "uid":"5365823342"}
        */
    }

}
// MARK: - 封装 AFN 网络方法
extension NetworkToos {
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    
    private func request(method:HMRequestMethod,URLString:String,parameters:[String:AnyObject]?,finish:HMRequestCallBack) {
    //定义成功回调
    let success = {
        (task:NSURLSessionDataTask,result:AnyObject)->Void in
        finish(result:result, error: nil)
        }
    //定义失败回调
        let failure = {
            (task:NSURLSessionDataTask,error:NSError)->Void
            in
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finish(result: nil, error: error)
        
        }
        if method == HMRequestMethod.GET {
        GET(URLString, parameters: parameters, success: success, failure: failure)
        }else {
        
        POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
    
}